package com.shuyuansystem.controller;



import com.auth0.jwt.interfaces.DecodedJWT;
import com.shuyuansystem.entity.Result;
import com.shuyuansystem.pojo.User;
import com.shuyuansystem.service.LoginService;
import com.shuyuansystem.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/Login")
public class UserController {
    private static final Logger log =  LoggerFactory.getLogger(UserController.class);
    String userType ;//用户类型
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LoginService loginService;

    @RequestMapping("/register")
    public boolean registerUser(@RequestBody User user) {
        ValueOperations<String,Object> ops = redisTemplate.opsForValue();
        String str =  ops.get(user.getEmail()).toString();
        System.out.println((user.getCaptcha()));
        if(str.equals(user.getCaptcha())) {
            // 调用服务层的注册方法进行注册
            boolean success = loginService.register(user);
            return success;
        }else {
            return false;
        }
    }

    @RequestMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        // 从请求体中获取用户名和密码封装在 User 对象中
        String username = user.getUsername();
        String password = user.getPassword();
        log.info("用户名：[{}]", user.getUsername());
        log.info("密码：[{}]", user.getPassword());
        Map<String, Object> map = new HashMap<>();
        boolean isValid = loginService.validateUser(username, password);
        if (isValid) {
            try {
                Map<String, String> payload = new HashMap<>();
                payload.put("id", loginService.findUserId(user));
                payload.put("name", user.getUsername());
                // 生成jwt令牌
                String token = JWTUtils.getToken(payload);
                log.info(token);
                map.put("state", true);
                map.put("userType", loginService.checkUserType(user));
                map.put("msg", "认证成功！");
                map.put("token", token);  // 响应token
            } catch (Exception e) {
                map.put("state", false);
                map.put("msg", e.getMessage());
            }
            return map;
        } else {
            map.put("state", false);
            map.put("msg", "用户名或密码错误");
            return map;
        }
    }
    @RequestMapping("/user/test")
    public Map<String, Object> test(HttpServletRequest request) {
            Map<String, Object> map = new HashMap<>();
            // 验证令牌  交给拦截器去做
            // 只需要在这里处理自己的业务逻辑
            String token = request.getHeader("token");
            DecodedJWT verify = JWTUtils.verify(token);
            log.info("用户id：[{}]",verify.getClaim("id").asString());
            log.info("用户名字：[{}]",verify.getClaim("name").asString());
            map.put("state", true);
            map.put("msg", "请求成功");

        return map;
    }
    @RequestMapping("/ChangePassworld")
    public Result ChangePassworld(@RequestBody User user) {
        // 验证邮箱是否与用户名匹配
        User storedUser = loginService.findUserByUsername(user.getUsername());
        if (storedUser == null ||!storedUser.getEmail().equals(user.getEmail())) {
            return new Result(false, "邮箱与用户名不匹配");
        }

        // 验证验证码
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        String storedCaptcha = (String) ops.get(user.getEmail());
        if (storedCaptcha == null ||!storedCaptcha.equals(user.getCaptcha())) {
            return new Result(false, "验证码错误");
        }

        // 修改密码
        boolean success = loginService.changePassword(user.getUsername(), user.getPassword());
        if (success) {
            return new Result(true, "密码修改成功");
        } else {
            return new Result(false, "密码修改失败");
        }
    }
}